package simple.manager;

import simple.persistence.dao.UserDAO;
import simple.persistence.dao.UserDAOInterface;
import simple.persistence.entity.User;

import javax.ejb.EJB;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class UserManagerBean implements UserManager {

    @EJB
    UserDAOInterface userDAO;

    private UserDAOInterface getUserDAO() {
        if (userDAO == null) {
            userDAO = new UserDAO();
        }
        return userDAO;
    }

    public List<User> getUsers() {
        if (getUserDAO().getUsers().isEmpty()) {
            seedUsers();
        }
        return getUserDAO().getUsers();
    }

    public List<User> findUsersBySearchTerm(String term) {
        if (getUserDAO().getUsers().isEmpty()) {
            seedUsers();
        }
        return getUserDAO().findUsersBySearchTerm(term);
    }

    private void seedUsers() {
        Date now = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(now);
        calendar.add(Calendar.YEAR, -30);
        calendar.set(Calendar.MONTH, 5);
        calendar.set(Calendar.DAY_OF_MONTH, 5);
        User u = new User();
//        u.setId(1L);
        u.setFirstName("John");
        u.setLastName("Doe");
        u.setBirthday(calendar.getTime());
        getUserDAO().saveUser(u);

        u = new User();
//        u.setId(2L);
        u.setFirstName("Mary");
        u.setLastName("Smith");
        calendar.add(Calendar.YEAR, 5);
        calendar.set(Calendar.MONTH, 2);
        calendar.set(Calendar.DAY_OF_MONTH, 10);
        u.setBirthday(calendar.getTime());
        getUserDAO().saveUser(u);

        u = new User();
//        u.setId(3L);
        u.setFirstName("Harold");
        u.setLastName("Jones");
        calendar.add(Calendar.YEAR, 2);
        calendar.set(Calendar.MONTH, 7);
        calendar.set(Calendar.DAY_OF_MONTH, 15);
        u.setBirthday(calendar.getTime());
        getUserDAO().saveUser(u);

    }
}
